//
//  BQSearchViewController.m
//  BeeQuick
//
//  Created by Vivitickey on 2017/4/27.
//  Copyright © 2017年 test. All rights reserved.
//

#import "BQSearchViewController.h"
#import <Masonry.h>
#import "BQSearchModel.h"
#import "UIColor+HMAddition.h"
#import "BQRightModel.h"
#import "BQShopCell.h"
#import "BQHomeLayout.h"
@interface BQSearchViewController ()<UITextFieldDelegate,UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic,weak) UIView *searchView;

@property (nonatomic,weak) UICollectionView *goodsCollectionView;

@end

static NSString *shop_Cell = @"shop_Cell";

@implementation BQSearchViewController{
    
    NSArray *_searchArray;
    
    UITextField *_textField;
    
    NSArray *_goodsArray;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];

    
    [self setupSearchBar];
    
    [self loadData];
    
    self.navigationController.navigationBar.barTintColor =[UIColor hm_colorWithR:252 G:207 B:47];
    
}

-(void)setupUI{


    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(clickRightBarButton)];
    
    
    
}



-(void)setupSearchBar{
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 290, 30)];
    
    
    //设置圆角效果
    bgView.layer.cornerRadius = 15;
    bgView.layer.masksToBounds = YES;
    
    bgView.backgroundColor = [UIColor hm_colorWithR:224 G:224 B:224];
    
    
    
    //输入框
    _textField = [[UITextField alloc] initWithFrame:CGRectMake(15, 0, CGRectGetWidth(bgView.frame) - 15, CGRectGetHeight(bgView.frame))];
    _textField.font = [UIFont systemFontOfSize:13];
    
    //清除按钮
    _textField.clearButtonMode =UITextFieldViewModeWhileEditing;
    
    _textField.delegate = self;
    //键盘属性
    _textField.returnKeyType = UIReturnKeySearch;
    
    //为textField设置属性占位符
    _textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@" 搜索内容" attributes:@{NSForegroundColorAttributeName:[UIColor lightGrayColor]}];
    
    _textField.textColor = [UIColor blackColor];
    
    
    [bgView addSubview:_textField];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:bgView];
    
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
//    NSLog(@"点击了搜索 %@",textField.text);
    
    FMDatabase *db = [[FMDatabase alloc] initWithPath:localDBPath];
    [db open];
    
    
    FMResultSet *set = [db executeQuery:@"SELECT * FROM BeeQuick WHERE name LIKE ?",[NSString stringWithFormat:@"%%%@%%",textField.text]];
    
        NSMutableArray *array = [NSMutableArray array];
        
        while ([set next]) {
            
            BQRightModel *model = [[BQRightModel alloc] init];
            
            model.name = [set stringForColumn:@"name"];
            model.market_price = [set stringForColumn:@"market_price"];
            model.partner_price = [set stringForColumn:@"partner_price"];
            model.pm_desc = [set stringForColumn:@"pm_desc"];
            model.img = [set stringForColumn:@"img"];
            model.specifics = [set stringForColumn:@"specifics"];
            model.count = [set intForColumn:@"count"];
            model.category_id = [set stringForColumn:@"category_id"];
            model.id = [set stringForColumn:@"id"];
            
            [array addObject:model];
            
        }
        
        _goodsArray = array.copy;
        
        [self.goodsCollectionView reloadData];
        

    [db close];
    
    return YES;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
        return CGSizeMake((_ScreenWidth - 10 * 3)/2, 230);
    
}



-(void)setupCollectionView{
    
    UICollectionView *goodsCollectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:[BQHomeLayout new]];
    
    goodsCollectionView.backgroundColor = [UIColor whiteColor];
    
    _goodsCollectionView = goodsCollectionView;
    
    goodsCollectionView.delegate = self;
    
    goodsCollectionView.dataSource = self;
    
    [self.view addSubview:goodsCollectionView];
    
    [goodsCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.offset(0);
        
        make.top.equalTo(self.searchView.mas_bottom);
    }];
    
    [goodsCollectionView registerNib:[UINib nibWithNibName:@"BQShopCell" bundle:nil] forCellWithReuseIdentifier:shop_Cell];
    
}


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return _goodsArray.count;
    
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    BQShopCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:shop_Cell forIndexPath:indexPath];
    
    
    cell.rightModel = _goodsArray[indexPath.row];
    
    return cell;
    
}


-(void)loadData{
    
    NSDictionary *para1 = @{@"call" : @6};
    
    [_AccountMgr POSTWithUrlString:search_url parameters:para1 success:^(id responseObject) {
        
        UIView *searchView = [self addButtonWithCityArray:responseObject[@"data"][@"hotquery"]];
        
        _searchView = searchView;
        
        [self.view addSubview:searchView];
        
        
        
        [searchView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).offset(100);
            
            make.width.equalTo(self.view);
            
            make.height.mas_offset(searchView.frame.size.height);
            
            
        }];
        
        [self setupCollectionView];
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];

}

//循环创建Button
-(UIView *)addButtonWithCityArray:(NSArray *)arr{
    
    
    UIView *SearchButtonView = [[UIView alloc]init];
    
    
    CGFloat w = 0;//保存前一个button的宽以及前一个button距离屏幕边缘的距离
    
    CGFloat h = 0;
    
    int tag = 0;
    
    UIView *buttonView1 = [[UIView alloc]init];
    UIView *buttonView2 = [[UIView alloc]init];
    UIView *buttonView3 = [[UIView alloc]init];
    
    for (int i = 0; i < arr.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        
        button.backgroundColor = [UIColor clearColor];
        
        //设置圆角
        button.layer.cornerRadius = 15;//2.0是圆角的弧度，根据需求自己更改
        button.layer.borderColor =[UIColor lightGrayColor].CGColor;//设置边框颜色
        button.layer.borderWidth = 0.5f;//设置边框颜色
        
        [button addTarget:self action:@selector(handleClick:) forControlEvents:UIControlEventTouchUpInside];
        [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        
        button.titleLabel.font = [UIFont systemFontOfSize:12];
        
        //根据计算文字的大小
        
        
        NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:12]};
        CGFloat length = [arr[i] boundingRectWithSize:CGSizeMake(_ScreenWidth, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.width;
        //为button赋值
        [button setTitle:arr[i] forState:UIControlStateNormal];
        
        //当button的位置超出屏幕边缘时换行  只是button所在父视图的宽度
        if(10 + w + length + 30 > _ScreenWidth){
            w = 0; //换行时将w置为0
            h = h + 40;//距离父视图也变化
            tag ++;
            button.frame = CGRectMake(10 + w, 0, length + 35, 30);//重设button的frame
        }else{
            
            
            //设置button的frame
            button.frame = CGRectMake(10 + w, 0, length + 35 , 30);
            
        }
        w = button.frame.size.width + button.frame.origin.x;
        
        
        switch (tag) {
            case 0:
                [buttonView1 addSubview:button];
                
                buttonView1.frame = CGRectMake((_ScreenWidth - w -length + 35)/2 , h, w + length + 35, 30);
                
                break;
            case 1:
                [buttonView2 addSubview:button];
                
                buttonView2.frame = CGRectMake((_ScreenWidth - w -length + 35)/2 , h, w + length + 35, 30);
                
                break;
            case 2:
                [buttonView3 addSubview:button];
                
                buttonView3.frame = CGRectMake((_ScreenWidth - w -length + 35)/2 , h, w + length + 35, 30);
                
            default:
                break;
        }
        
    }
    
    
    
    [SearchButtonView addSubview:buttonView1];
    
    [SearchButtonView addSubview:buttonView2];
    
    [SearchButtonView addSubview:buttonView3];
    
    SearchButtonView.frame = CGRectMake(0, 0, _ScreenWidth, h + 30);
    
    return SearchButtonView;
    
}
- (void)clickRightBarButton{
    
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)handleClick:(UIButton *)btn{
    
    FMDatabase *db = [[FMDatabase alloc] initWithPath:localDBPath];
    [db open];

        FMResultSet *set =  [db executeQuery:@"SELECT * FROM BeeQuick WHERE name LIKE ?",[NSString stringWithFormat:@"%%%@%%",btn.titleLabel.text]];
        
        NSMutableArray *array = [NSMutableArray array];
        
        while ([set next]) {
            
            BQRightModel *model = [[BQRightModel alloc] init];
            
            model.name = [set stringForColumn:@"name"];
            model.market_price = [set stringForColumn:@"market_price"];
            model.partner_price = [set stringForColumn:@"partner_price"];
            model.pm_desc = [set stringForColumn:@"pm_desc"];
            model.img = [set stringForColumn:@"img"];
            model.specifics = [set stringForColumn:@"specifics"];
            model.count = [set intForColumn:@"count"];
            model.category_id = [set stringForColumn:@"category_id"];
            model.id = [set stringForColumn:@"id"];
            
            [array addObject:model];
            
            
            
        }
        
        _goodsArray = array.copy;
        
        [self.goodsCollectionView reloadData];

        [db close];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [_textField resignFirstResponder];
}
@end
